package com.movie2.controller;

import com.movie2.config.MyConstants;
import com.movie2.model.entity.Message;
import com.movie2.model.entity.User;
import com.movie2.service.MessageService;
import com.movie2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/message")
@CrossOrigin
@Slf4j
public class MessageController {
    @Autowired
    MessageService messageService;
    @Autowired
    UserService userService;

    @GetMapping("")
    public List<Map<String,Object>> getMessage(){
        log.info("获得留言列表；MessageController -> getMessage()");
        List<Map<String,Object>> mapList=new ArrayList<>();
        List<Message> messageList= messageService.selectAllMessages();
        for (Message message : messageList) {
            Map<String,Object> map=new HashMap<>();
            User user=userService.selectByPrimaryKey(message.getUid());
            map.put("message",message);
            user.setAvatar(MyConstants.MY_URL+user.getAvatar());
            map.put("user",user);
            mapList.add(map);
        }
        return mapList;
    }

    @PostMapping("/add")
    public Map<String,Object> addMessage(@RequestBody Message message){
        log.info("添加留言：MessageController -> addMessage()");
        Map<String,Object> map=new HashMap<>();
        int count=messageService.insert(message);
        if (count==1){
            map.put("success","ok");
        }else {
            map.put("success","fail");
        }
        return map;

    }
}
